#!/bin/bash
#set -x
shPath=$(cd $(dirname $0);pwd)
cd $shPath

if [[ $# == 0 ]]; then
  keyword="dbagent/agent"
  pid=`ps aux|grep $keyword|grep -v grep|awk -F'[ ]+' '{{print $2}}'`
else
 pid=$1
fi

if [ -e "/usr/bin/iostat" ]; then
	sys_read=`iostat -d -k|tail -n +4|head -n -1|awk -F"[ ]+" '{print $3}'|awk '{sum += $1};END {print sum}'`
	sys_write=`iostat -d -k|tail -n +4|head -n -1|awk -F"[ ]+" '{print $4}'|awk '{sum += $1};END {print sum}'`
else
	sys_read=0.00
	sys_write=0.00
fi

if [[ "$pid" == ""  ]] || [ ! -e "/usr/bin/pidstat" ];then
  pid_read=0.00
  pid_write=0.00
else
  pid_read=`pidstat -d -p ${pid}|tail -n1 |awk -F"[ ]+" '{print $4}'`
  pid_write=`pidstat -d -p ${pid}|tail -n1 |awk -F"[ ]+" '{print $5}'`
fi

#sys_cpu=`top -b -n 1 |grep %Cpu | awk -F'[ ]+' '{print $2}'`
sys_cpu=`top -b -n 1 |grep %Cpu | awk -F':' '{print $2}'|awk -F' ' '{print $1}'`
#total_mem=`free -m |head -n2 |tail -n1|awk -F'[ ]+' '{print $2}'`
#usaged_mem=`free -m |head -n3 |tail -n1|awk -F'[ ]+' '{print $3}'`
#sys_mem=$(($usaged_mem*100/$total_mem))
sys_mem=`free -m |head -n2 |tail -n1|awk '{print $3*100/$2}'`

if [[ $# == 0 ]]; then
agent_cpu=`ps aux|grep $keyword|grep -v grep|awk -F'[ ]+' '{{print $3}}'`
agent_mem=`ps aux|grep $keyword|grep -v grep|awk -F'[ ]+' '{{print $4}}'`
else
agent_cpu=`ps aux|awk -v pid=$pid '$2==pid {print $3}'`
agent_mem=`ps aux|awk -v pid=$pid '$2==pid {print $4}'`
fi
if [[ "$agent_cpu" == "" ]];then
  agent_cpu=0.00
fi

if [[ "$agent_mem" == "" ]];then
  agent_mem=0.00
fi

if [[ "$pid" == ""  ]];then
  agent_mem_size=0.00
else
  agent_mem_size=`cat /proc/$pid/status |grep VmRSS |awk -F'[\t ]+' '{{print $2}}'`
  if [[ "${agent_mem_size}" == "" ]];then
    agent_mem_size=0.00
  else
    agent_mem_size=$(($agent_mem_size/1024))
  fi
fi

echo "$sys_read;$sys_write;$pid_read;$pid_write;$sys_cpu;$sys_mem;$agent_cpu;$agent_mem;$agent_mem_size"
